const upload = document.querySelector('#upload')
const avatar = document.querySelector('.figure img')
const btn = document.querySelector('#btn')
// 昵称
const nickname = document.querySelector('[name=nickname]')

// 省市区
const province = document.querySelector('[name=province]')
const city = document.querySelector('[name=city]')
const area = document.querySelector('[name=area]')
axios.defaults.baseURL = 'http://ajax-api.itheima.net'

// 渲染函数
async function getname() {
  const res = await axios.get('/api/settings')
  console.log(res);
  nickname.value = res.data.data.nickname
  avatar.src = res.data.data.avatar
}

// 上传函数
document.querySelector('form').addEventListener('submit', function (e) {
  e.preventDefault()
})
btn.addEventListener('click', async function () {

  const res = await axios.put('/api/settings', {

    nickname: nickname.value,
    province: province.value,
    city: city.value,
    area: area.value,
    avatar: localStorage.getItem('imgurl')

  })
});

// 省市县渲染
(function () {
  getname()
  // 获取省数据
  async function getProvince() {
    const res = await axios.get('/api/province')
    console.log(res);

    let arr = res.data.data.map((res, i) => {
      return `<option value="${res}">${res}</option>`
    }).join('')
    province.innerHTML = arr
  }
  async function getCity(pname) {
    const res = await axios.get('/api/city', {
      params: {
        pname: pname
      },
    })
    console.log(res);
    let arr = res.data.data.map((res, i) => {
      return `<option value="${res}">${res}</option>`
    }).join('')
    city.innerHTML = arr
  }

  async function getArea(params, cname) {
    const res = await axios.get('/api/area', {
      params: {
        pname: params,
        cname: cname,
      }
    })
    console.log(res);
    let arr = res.data.data.map((res, i) => {
      return `<option value="${res}">${res}</option>`
    }).join('')
    area.innerHTML = arr
  }
  getArea('北京', '北京市')
  getCity('北京')
  getProvince()

  province.addEventListener('change', async function () {
    await getCity(province.value)

    await getArea(province.value, city.value)
  })
  city.addEventListener('change', function () {
    getArea(province.value, city.value)
  })
})();
// 图片上传函数
(function () {
  async function postimg(fd) {
    const res = await axios.post('/api/file', fd)
    console.log(res);
    localStorage.setItem('imgurl', res.data.data.url)
  }
  avatar.addEventListener('click', function () {
    upload.click()
  })
  upload.addEventListener('change', async function () {

    const img = this.files[0]
    if (!img) {
      return
    }
    const fd = new FormData()
    fd.append('avatar', img)
    console.log(this.files)
    console.log(img);
    postimg(fd)

  })

})();